package com.gin.no_gay_alliance.customview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.AttributeSet;
import android.webkit.WebSettings;
import android.webkit.WebView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.gin.nga.bbscode.entity.BbsTag;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.utils.BbsCodeUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用来显示正文的WebView
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/23 09:12
 **/
public class ContentWebView extends WebView {
    public static final String TAG = ContentWebView.class.getSimpleName();
    public static final String PLACEHOLDER_CONTENT = "[正文占位]";
    public static final String PLACEHOLDER_STYLE_CLASS = "[CLASS占位]";
    String template;

    String contentData;

    public ContentWebView(@NonNull Context context) {
        super(context);
        init();
    }

    public ContentWebView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ContentWebView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public ContentWebView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    public void loadDataWithBaseURL(@Nullable String baseUrl, @NonNull String data) {
        loadDataWithBaseURL(baseUrl, data, "text/html", "UTF-8", null);
    }

    /**
     * 加载一个节点列表
     *
     * @param nodes 节点列表
     */
    public void loadNodes(List<BbsTag> nodes) {
        template = template != null ? template : getTemplate();
        // 节点转换成的HTML
        String content = BbsCodeUtils.toHtml(nodes);
        // 根据当前应用的主题, 决定最外层div的class
        int themeResId = MyApplication.app.managerFactory.getThemeManager().getThemeResId();
        String parentClass = themeResId == R.style.Theme_Nga_Black ? "black_text_color" : "default_text_color";
        // 替换模板中的占位符
        String data = template
                .replace(PLACEHOLDER_STYLE_CLASS, parentClass)
                .replace(PLACEHOLDER_CONTENT, content);
        // 加载
        if (data.equals(contentData)) {
//            Log.d(TAG, "loadNodes: 数据未变化, 忽略加载");
            return;
        }
        contentData = data;
        loadDataWithBaseURL(null, data);
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void init() {
        //禁用滚动条
        setVerticalScrollBarEnabled(false);
        setHorizontalScrollBarEnabled(false);
        //背景透明
        setBackgroundColor(0);

        WebSettings settings = getSettings();
        //设置WebView属性,运行执行js脚本
        settings.setJavaScriptEnabled(true);
        //默认字体大小12
        settings.setDefaultFontSize(14);
        // 阻止图片自动加载
        settings.setBlockNetworkImage(true);
        // 关闭硬件加速
//        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    /**
     * 从assets文件夹中加载模板
     *
     * @return 模板
     */
    public String getTemplate() {
        try {
            AssetManager assetManager = getContext().getAssets();
            InputStream is = assetManager.open("template.html");
            InputStreamReader isReader = new InputStreamReader(is);
            BufferedReader bfReader = new BufferedReader(isReader);
            return bfReader.lines().collect(Collectors.joining());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
